<template>
  <view class="learning-view">
    <!-- 详情页 -->
    <Detail
      :show="detailVisible"
      :control="control"
      :entry="entry"
      :picker-keys="pickerKeys"
      @open-feedback="openFeedbackView"
      @close="onDetailClose"
    />

    <!-- 评价反馈 (程序调整) -->
    <FeedbackProposal v-model:show="feedbackVisible" :control="control" @close="onFeedbackProposalClose" />
  </view>
</template>

<script setup lang="ts">
import type { DishwasherController } from '@/controller/Dishwasher/definition'
import { getLearningModalObserves } from '@/controller/Dishwasher/Learning/learning'
import { type LearningViewEntry, LearningViewScene } from './constants'
import Detail from './view/detail.vue'
import FeedbackProposal from './view/feedbackProposal.vue'
import { getPageQuery, showLoading } from '@/utils/mpHelper'

const props = defineProps<{
  show: boolean
  control: DishwasherController.Control
  scene: LearningViewScene | null
  entry: LearningViewEntry
  /**
   * ActionBar入口 需要以下参数
   *  - 调节参数Key 配置
   */
  pickerKeys?: string[] // 需要展示为Picker组件的 Key
}>()
const emit = defineEmits<{
  (e: 'update:show', show: boolean): void
}>()
defineExpose({
  openFeedbackView,
})

/**
 * 页面状态
 */
const modalObserves = getLearningModalObserves({
  onSwitchToOtherProgram: () => closeLearningView(),
})
watch(
  () => props.show,
  async (show) => {
    if (show) {
      props.control.remote.addBatchObserves(modalObserves)
      loadData()
    } else {
      props.control.remote.removeBatchObserves(modalObserves)
    }
  }
)
function closeLearningView() {
  emit('update:show', false)
}

// 接收评价反馈通知时 打开提示框
watch(
  () => props.control.store.feedbackNoticeReceived,
  (received) => {
    // 未收到消息 或 详情页打开时，不显示提示框、评价弹框
    if (!received || detailVisible.value) return

    /**
     * Loading页跳转来详情页时，直接打开评价反馈弹框
     */
    const query = getPageQuery()
    const utmSource = query?.utmSource
    if (utmSource === 'learning_dishwasher_feedback_001') {
      openFeedbackView()
    }
  },
  { immediate: true }
)

async function loadData() {
  try {
    await showLoading(() => Promise.all([props.control.remote.loadAllSetting(), props.control.remote.loadAllStatus()]))
  } catch (e) {
    console.error(e)
    closeLearningView()
  }
}

/**
 * 详情页
 */
const detailVisible = ref(false)
function onDetailClose() {
  // 详情页关闭时 关闭LearningView
  closeLearningView()
}

/**
 * 评价反馈
 */
const feedbackVisible = ref(false)
function openFeedbackView() {
  feedbackVisible.value = true
}
function onFeedbackProposalClose() {
  // 详情页关闭评价返回 不关闭
  if (props.scene === LearningViewScene.Detail) return

  closeLearningView()
}

/**
 * 根据场景 触发对应视图显示
 */
// 详情页
watchEffect(() => {
  detailVisible.value = props.show && props.scene === LearningViewScene.Detail
})

// 评价反馈
watchEffect(() => {
  feedbackVisible.value = props.show && props.scene === LearningViewScene.Feedback
})
</script>
